<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="usersData.query"
            clearable
            @clear="getUsersList"
            placeholder="请输入内容"
            class="input-with-select"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserStatusHidden = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="users" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeStatus(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editMessage(scope.row)"
            ></el-button>
            <el-button
              @click="removeUser(scope.row.id)"
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="usersData.pagenum"
        :page-sizes="[1, 2, 4, 8]"
        :page-size="usersData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserStatusHidden"
      @close="resetForm"
      width="50%"
    >
      <el-form
        ref="addUserRef"
        :model="addUserForm"
        :rules="addRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserStatusHidden = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑信息"
      @close="resetEditForm"
      :visible.sync="editUserStatusHidden"
      width="50%"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="用户名 :">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱 :">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机 :">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserStatusHidden = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 邮箱验证规则
    const checkEmail = (rules, value, callback) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(value)) {
        return callback()
      }
      return callback(new Error('邮箱输入不合法'))
    }
    // 手机验证规则
    const checkMobile = (rules, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        return callback()
      }
      return callback(new Error('手机号码输入不合法'))
    }
    return {
      // 可以根据这个搜索游览器的vue视图
      name: 'users',
      // 传递后台的参数
      usersData: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      // 用户列表
      users: [],
      total: 0,
      addUserStatusHidden: false,
      editUserStatusHidden: false,
      // 用户表单
      addUserForm: {
        username: 'dd123',
        password: '123456',
        email: 'qq@qq.com',
        mobile: '13397166111'
      },
      // 编辑表单
      editForm: {
        username: 'zs',
        email: 'qq@qq.com',
        mobile: '13397166111'
      },
      // 表单验证规则
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    this.getUsersList()
  },

  methods: {
    // 获取用户列表
    async getUsersList () {
      const { data: res } = await this.$axios.get('/users', {
        params: this.usersData
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.users = res.data.users
      this.total = res.data.total
    },
    // 改变每页条数时候
    handleSizeChange (val) {
      this.usersData.pagesize = val
      this.getUsersList()
    },
    // 改变页码时候
    handleCurrentChange (val) {
      this.usersData.pagenum = val
      this.getUsersList()
    },
    // 更新用户状态
    async changeStatus (item) {
      // console.log(item)
      const { data: res } = await this.$axios.put(
        `users/${item.id}/state/${item.mg_state}`
      )
      if (res.meta.status !== 200) {
        this.$message.error('更新用户状态失败')
        item.mg_state = !item.mg_state
        return
      }
      this.$message.success('更新用户状态成功')
    },
    // 关闭对话重置表单
    resetForm () {
      this.$refs.addUserRef.resetFields()
    },
    // 提交添加用户表单
    submitForm () {
      this.$refs.addUserRef.validate(async flage => {
        if (!flage) return
        // console.log('提交后台表单')
        const { data: res } = await this.$axios.post('/users', this.addUserForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加用户成功')
        this.addUserStatusHidden = false
        this.getUsersList()
      })
    },
    // 编辑用户信息
    editMessage (item) {
      // console.log(item)
      this.editUserStatusHidden = true
      this.editForm = item
    },
    resetEditForm () {
      this.$refs.editFormRef.resetFields()
    },
    submitEditForm () {
      this.$refs.editFormRef.validate(async flage => {
        if (!flage) return
        // console.log('提交表单')
        const { data: res } = await this.$axios.put(
          '/users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editUserStatusHidden = false
        this.getUsersList()
      })
    },
    removeUser (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '删除',
        type: 'warning'
      })
        .then(async () => {
          // 点击了确认
          console.log(id)
          const { data: res } = await this.$axios.delete('users/' + id)
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.$message.success('删除成功')
          this.getUsersList()
        })
        .catch(() => {
          // 点击了取消
          this.$message('已取消删除')
        })
    }
  }
}
</script>

<style scoped lang="less"></style>
